import PhysiologicalMonitoring from '@/components/PhysiologicalMonitoring';
import { create_assess, get_video_list_simple } from '@/services/assrssment';
import { bind_patient_select } from '@/services/guide';
import { get_patient_info } from '@/services/patient';
import { filedlist } from '@/services/platformuser';
import age from '@/utils/age';
import deepClone from '@/utils/deepClone';
import question_list from '@/utils/gauge';
import timeToHms from '@/utils/time';
import { InfoCircleTwoTone } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import {
  Button,
  Card,
  Checkbox,
  Divider,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Space,
  Tabs,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import './index.less';

type GithubIssueItem = {
  id: number;
  name: string;
  type_name: string;
  video_time: string;
  time: string;
  url: string;
};
var question_results: any = [];
var days = '1';
const Becovery_assessment = () => {
  const actionRef = useRef<ActionType>();

  // 存储用户详情
  const [memberinfo, setmemberinfo] = useState<any>(undefined);
  // 当前医生信息
  const { initialState, setInitialState } = useModel('@@initialState');
  // 存储当前患者id
  const [editId, seteditId] = useState(undefined);
  // 视频类型
  const [video_field, setvideo_field] = useState([]);
  // 添加居家处方
  const [video_data, setvideo_data] = useState([]);

  const [total_nums, settotal_nums] = useState(0);
  const [total_time, settotal_time] = useState('00:00:00');

  // 右侧视频列表
  const [right_video, setright_video] = useState([]);
  const [right_video2, setright_video2] = useState([]);
  // 居家处方搜索项
  const [search_name, setsearch_name] = useState('');
  const [videotype, setvideotype] = useState();
  const [search_name2, setsearch_name2] = useState('');
  const [videotype2, setvideotype2] = useState();
  // 播放视频
  const [viewButton, setviewButton] = useState(false);
  const [videoplay, setvideoplay] = useState('');
  // 提交评估模态框状态
  const [commitVisible, setcommitVisible] = useState(false);

  // 页面初始化
  useEffect(() => {
    get_video_list(0);
    get_video_list(1);
    // get_prescription_list();
    get_field();
  }, []);

  //重新计算总时长和视频条数
  useEffect(() => {
    var sum = 0;
    if (video_data.length != 0) {
      video_data.map((item: any, key) => {
        // console.log(item.times);
        if (item.times != undefined) {
          sum += parseInt(String(item.time * item.times));
        } else {
          sum += parseInt(item.time);
        }
        settotal_time(timeToHms(sum));
      });
    } else {
      // console.log(1);
      settotal_time('00:00:00');
    }
  }, [video_data]);

  // 患者列表下拉框
  const get_patient_list = async () => {
    let params: any = await bind_patient_select({ id: initialState?.currentUser?.id });
    let res: any = [];
    console.log('params', params);
    params.data.map((item: any) => {
      let temp: any = {};
      temp['label'] = item.username + '/' + item.phone + '/' + item.id_card;
      temp['value'] = parseInt(item.id);
      res.push(temp);
    });
    return res;
  };

  // 获取视频
  const get_video_list = async (key: number) => {
    let request_body: { source: number; name?: string; type?: number } = {
      source: key,
    };
    if (key == 1) {
      if (search_name != '') {
        request_body.name = search_name;
      }
      if (videotype != undefined) {
        request_body.type = videotype;
      }
    } else {
      if (search_name2 != '') {
        request_body.name = search_name2;
      }
      if (videotype2 != undefined) {
        request_body.type = videotype2;
      }
    }
    const res = await get_video_list_simple(request_body);
    console.log('视频列表', res);
    // 0平台视频 1自有视频
    if (key == 1) {
      setright_video(res.data);
    } else {
      setright_video2(res.data);
    }
  };
  // 获取视频分类
  const get_field = async () => {
    let request_body = {
      type: 'video_type',
    };
    let params = await filedlist(request_body);
    let res: any = [];
    params.data.map((item: any) => {
      let temp: any = {};
      temp['label'] = item.value;
      temp['value'] = parseInt(item.key);
      res.push(temp);
    });
    console.log('视频分类', res);
    setvideo_field(res);
  };

  // 处方添加视频
  const add_video = (record: any) => {
    let res = deepClone(video_data);
    let temp: any = {};
    temp['key'] = res.length;
    temp['id'] = record.id;
    temp['name'] = record.name;
    temp['type_name'] = record.type_name;
    temp['time'] = record.video_time;
    temp['times'] = 1;
    res.push(temp);
    setvideo_data(res);
    settotal_nums(res.length);
  };
  // 修改视频频次
  const change_times = (index: number, times: string) => {
    let res = deepClone(video_data);
    res[index].times = parseInt(times ? times : '0');
    setvideo_data(res);
  };

  // 删除添加视频
  const edlit_video = (index: number) => {
    let res = deepClone(video_data);
    res.splice(index, 1);
    settotal_nums(res.length);
    setvideo_data(res);
  };

  // 查看视频
  const isShowEdit = (status: boolean, url: string) => {
    // console.log(url);
    setviewButton(status);
    setvideoplay(url);
  };
  // 选中患者信息
  const getoldman_info = async (value: any) => {
    setmemberinfo(undefined);
    seteditId(value);
    let request_body = {
      id: value,
    };
    let params: any = await get_patient_info(request_body);
    console.log('患者信息', params);

    if (params.code == 200) {
      setmemberinfo(params.data);
      // console.log(params.data);
    }
  };

  // radio 单选框
  const radio_change = (e: any, question_id: number) => {
    // console.log(question_id, 'radio checked', e.target.value);
    question_results[question_id - 1] = {
      question_id: question_id,
      question_answer: e.target.value,
      type: 'radio',
    };
    // console.log(question_results);
  };

  // checkbox 多选框
  const checkbox_change = (value: any, question_id: number) => {
    // console.log(question_id, 'checked = ', value);
    let question_answer = '';
    value.forEach((e: any) => {
      question_answer += e + ',';
    });
    question_answer = question_answer.slice(0, -1);
    question_results[question_id - 1] = {
      question_id: question_id,
      question_answer: question_answer,
      type: 'checkbox',
    };
  };

  // input 输入框
  const input_change = (e: any, question_id: number) => {
    // console.log(e.target.value);
    question_results[question_id - 1] = {
      question_id: question_id,
      question_answer: e.target.value,
      type: 'input',
    };
    // console.log(question_results);
  };

  //确认提交确定按钮
  const delOk = async () => {
    // 处理视频列表
    let video: any = [];
    let video_data_clone = deepClone(video_data);
    if (editId == undefined) {
      message.error('请选择患者');
      return;
    }
    if (video_data_clone.length == 0) {
      message.error('请填写居家处方');
      return;
    }
    video_data_clone.map((item: any) => {
      let temp: any = {};
      temp['video_id'] = item.id;
      temp['times'] = item.times != undefined ? item.times : 1;
      video.push(temp);
    });

    let resresults: any = [];
    // let res;
    if (question_results.length != 0) {
      question_results.map((item: any) => {
        let temp: any = {};
        temp['question_id'] = item.question_id;
        temp['question_answer'] = item.question_answer;
        temp['type'] = item.type;
        resresults.push(temp);
      });
    }
    // 请求体
    let request_body = {
      old_id: editId,
      assess_content: JSON.stringify(resresults),
      video_data: JSON.stringify(video),
      days,
    };
    // 提交评估
    let res: any = await create_assess(request_body);
    if (res.code === 200) {
      message.success('提交评估成功');
      setcommitVisible(false);
      setTimeout(() => {
        location.reload();
      }, 500);
    }
  };

  // 自有视频表格
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '视频名称',
      dataIndex: 'name',
      align: 'center',
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <Space>
            <Input
              placeholder={`请输入视频名称`}
              value={search_name}
              allowClear
              onChange={(e) => setsearch_name(e.target.value)}
            />

            <Button
              type="primary"
              onClick={() => get_video_list(1)}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
          </Space>
        </div>
      ),
    },
    {
      title: '视频分类',
      dataIndex: 'type_name',
      align: 'center',
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <Space>
            <Select
              style={{ width: 150 }}
              placeholder={`请选择视频分类`}
              allowClear
              onChange={(value) => {
                setvideotype(value);
              }}
            >
              {video_field != undefined
                ? video_field.map((a: any, b) => {
                  return (
                    <Select.Option key={a.value} value={a.value}>
                      {a.label}
                    </Select.Option>
                  );
                })
                : ''}
            </Select>

            <Button
              type="primary"
              onClick={() => get_video_list(1)}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
          </Space>
        </div>
      ),
    },
    {
      title: '视频时长',
      hideInSearch: true,
      key: 'video_time',
      dataIndex: 'video_time',
      align: 'center',
      render: (_, record) => {
        return timeToHms(record.video_time);
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="add"
          type="link"
          onClick={() => {
            add_video(record);
          }}
          style={{ marginRight: '5px' }}
        >
          添加
        </Button>,
        <Button
          key="check"
          type="link"
          onClick={() => {
            isShowEdit(true, record.url);
          }}
        >
          播放
        </Button>,
      ],
    },
  ];

  // 平台视频表格
  const columns2: ProColumns<GithubIssueItem>[] = [
    {
      title: '视频名称',
      dataIndex: 'name',
      align: 'center',
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <Space>
            <Input
              placeholder={`请输入视频名称`}
              onChange={(e) => setsearch_name2(e.target.value)}
              value={search_name2}
              allowClear
            />

            <Button
              type="primary"
              onClick={() => get_video_list(0)}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
          </Space>
        </div>
      ),
    },
    {
      title: '视频分类',
      dataIndex: 'type_name',
      align: 'center',
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <Space>
            <Select
              style={{ width: 150 }}
              placeholder={`请选择视频分类`}
              allowClear
              onChange={(value) => {
                setvideotype2(value);
              }}
            >
              {video_field != undefined
                ? video_field.map((a: any, b) => {
                  return (
                    <Select.Option key={a.value} value={a.value}>
                      {a.label}
                    </Select.Option>
                  );
                })
                : ''}
            </Select>
            <Button
              type="primary"
              onClick={() => get_video_list(0)}
              size="small"
              style={{ width: 90 }}
            >
              搜索
            </Button>
          </Space>
        </div>
      ),
    },
    {
      title: '视频时长',
      align: 'center',
      hideInSearch: true,
      key: 'video_time',
      dataIndex: 'video_time',
      render: (_, record) => {
        return timeToHms(record.video_time);
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="add"
          type="link"
          onClick={() => {
            add_video(record);
          }}
          style={{ marginRight: '5px' }}
        >
          添加
        </Button>,
        <Button
          key="check"
          type="link"
          onClick={() => {
            isShowEdit(true, record.url);
          }}
        >
          播放
        </Button>,
      ],
    },
  ];

  // 居家处方左侧表格
  const columns3: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      key: 'index',
      align: 'center',
      render: (_, record, index) => `${index + 1}`,
    },
    {
      title: '视频名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },

    {
      title: '视频类型',
      dataIndex: 'type_name',
      key: 'type_name',
      align: 'center',
    },

    {
      title: '视频时长',
      hideInSearch: true,
      key: 'time',
      dataIndex: 'time',
      render: (_, record) => {
        return timeToHms(record.time);
      },
    },

    {
      title: '训练频次',
      align: 'center',
      render: (_, record, index) => {
        return <Input defaultValue={1} onChange={(e) => change_times(index, e.target.value)} />;
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      valueType: 'option',
      render: (_, record, index) => {
        return (
          <a
            key="del"
            onClick={() => {
              edlit_video(index);
            }}
          >
            删除
          </a>
        );
      },
    },
  ];

  return (
    <PageContainer
      breadcrumb={false}
      header={{
        extra: [
          <Button
            key="submit"
            style={{ padding: '0 12px' }}
            type="primary"
            disabled={editId ? false : true}
            onClick={() => setcommitVisible(true)}
          >
            提交
          </Button>,
        ],
      }}
    >
      <ProForm submitter={false}>
        <Card>
          <ProFormGroup>
            <ProFormSelect
              width={270}
              name="old_id"
              request={get_patient_list}
              onChange={getoldman_info}
              label="患者姓名"
              rules={[
                {
                  required: true,
                  message: '请选择患者姓名',
                },
              ]}
            />
            {memberinfo === undefined ? (
              <>
                <ProFormText width={270} label="身份证号" disabled={true} />
                <ProFormText width={270} label="性别" disabled={true} />
                <ProFormText width={270} label="出生日期" disabled={true} />
                <ProFormText width={270} label="年龄" disabled={true} />
                <ProFormText width={270} label="手机号" disabled={true} />
                <ProFormText width={270} label="民族" disabled={true} />
                <ProFormText width={270} label="地址" disabled={true} />
                <ProFormText width={270} label="详细地址" disabled={true} />
              </>
            ) : (
              <>
                <ProFormText
                  width={270}
                  name="id_card"
                  label="身份证号"
                  disabled={true}
                  // @ts-ignore
                  value={memberinfo.id_card}
                />
                <ProFormText
                  width={270}
                  disabled={true}
                  name="sex"
                  label="性别"
                  // @ts-ignore
                  value={memberinfo.sex == 0 ? '未知' : memberinfo.sex == 1 ? '男' : '女'}
                />
                <ProFormText
                  width={270}
                  disabled={true}
                  name="birth"
                  label="出生日期"
                  // @ts-ignore
                  value={memberinfo.birth}
                />
                <ProFormText
                  width={270}
                  name="age"
                  label="年龄"
                  disabled={true}
                  // @ts-ignore
                  value={age(memberinfo.birth)}
                />
                <ProFormText
                  width={270}
                  name="phone"
                  disabled={true}
                  label="手机号"
                  // @ts-ignore
                  value={memberinfo.phone}
                />
                <ProFormText
                  width={270}
                  disabled={true}
                  name="nation_name"
                  label="民族"
                  // @ts-ignore
                  value={memberinfo.nation_name}
                />
                <ProFormText
                  width={270}
                  disabled={true}
                  name="family_address"
                  label="地址"
                  // @ts-ignore
                  value={memberinfo.family_address}
                />
                <ProFormText
                  width={270}
                  name="area"
                  disabled={true}
                  label="详细地址"
                  // @ts-ignore
                  value={
                    memberinfo.family_address
                      ? [
                        memberinfo.province_name +
                        memberinfo.city_name +
                        memberinfo.area_name +
                        memberinfo.family_address,
                      ]
                      : ''
                  }
                />
              </>
            )}
          </ProFormGroup>
        </Card>
        <Card style={{ marginTop: '20px' }}>
          <Tabs
            defaultActiveKey="生理监测"
            items={[
              {
                key: '生理监测',
                label: '生理监测',
                children: (
                  <div style={{ marginTop: '10px' }}>
                    <PhysiologicalMonitoring patientId={editId}></PhysiologicalMonitoring>
                  </div>
                ),
              },
              {
                key: '评估',
                label: '评估',
                children: (
                  <div style={{ display: 'flex', flexWrap: 'wrap' }} key="assessment">
                    {question_list.map((item, index) => {
                      if (item.question_id != 26) {
                        return (
                          <div className="question_item" key={index}>
                            <div className="question_title">{item.question_title}</div>
                            <div className="question_answer">
                              {item.type === 'radio' ? (
                                <Radio.Group onChange={(e) => radio_change(e, item.question_id)}>
                                  {item.children != undefined
                                    ? item.children.map((a, b) => {
                                      return (
                                        <Radio key={a.key} value={a.value}>
                                          {a.key}
                                        </Radio>
                                      );
                                    })
                                    : ''}
                                </Radio.Group>
                              ) : (
                                ''
                              )}

                              {item.type === 'checkbox' ? (
                                <Checkbox.Group
                                  onChange={(e) => checkbox_change(e, item.question_id)}
                                >
                                  {item.children != undefined
                                    ? item.children.map((a, b) => {
                                      return (
                                        <Checkbox key={a.key} value={a.value}>
                                          {a.key}
                                        </Checkbox>
                                      );
                                    })
                                    : ''}
                                </Checkbox.Group>
                              ) : (
                                ''
                              )}

                              {item.type === 'input' ? (
                                <Input
                                  style={{
                                    width: '150px',
                                    height: '25px',
                                    display: 'inline',
                                  }}
                                  onChange={(e) => input_change(e, item.question_id)}
                                />
                              ) : (
                                ''
                              )}
                            </div>
                          </div>
                        );
                      } else {
                        return (
                          <div className="question_item2" key={index}>
                            <div className="question_title">{item.question_title}</div>
                            <div className="question_answer">
                              {item.type === 'checkbox' ? (
                                <Checkbox.Group
                                  onChange={(e) => checkbox_change(e, item.question_id)}
                                >
                                  {item.children != undefined
                                    ? item.children.map((a, b) => {
                                      return (
                                        <Checkbox
                                          key={a.key}
                                          value={a.value}
                                          style={{
                                            width: '172px',
                                            float: 'left',
                                            marginLeft: '8px',
                                            marginBottom: '35px',
                                          }}
                                        >
                                          {a.key}
                                        </Checkbox>
                                      );
                                    })
                                    : ''}
                                </Checkbox.Group>
                              ) : (
                                ''
                              )}
                            </div>
                          </div>
                        );
                      }
                    })}
                  </div>
                ),
              },
              {
                key: '居家处方',
                label: '居家处方',
                children: (
                  <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                    <ProTable
                      style={{ width: '50%', height: '547px' }}
                      columns={columns3}
                      search={false}
                      options={false}
                      actionRef={actionRef}
                      dataSource={video_data}
                      pagination={false}
                      rowKey={(record) => record.id}
                      dateFormatter="string"
                      scroll={{ y: 400 }}
                      footer={() => {
                        return (
                          <div style={{ overflow: 'hidden' }}>
                            <div style={{ float: 'left', fontSize: '16px', lineHeight: '30px' }}>
                              共计<span style={{ color: 'red' }}>{total_nums}</span>条 总时长：
                              <span style={{ color: 'red' }}>{total_time}</span>
                            </div>
                            <div style={{ float: 'right' }}>
                              <span>训练周期 : </span>
                              <Select
                                defaultValue="1"
                                style={{ width: 120 }}
                                onChange={(value: string) => {
                                  days = value;
                                }}
                                disabled={editId ? false : true}
                              >
                                <Select.Option value="1">1天</Select.Option>
                                <Select.Option value="3">3天</Select.Option>
                                <Select.Option value="5">5天</Select.Option>
                                <Select.Option value="7">7天</Select.Option>
                                <Select.Option value="15">15天</Select.Option>
                                <Select.Option value="30">30天</Select.Option>
                              </Select>
                            </div>
                          </div>
                        );
                      }}
                    />
                    {/* 处方右侧表格 */}
                    <div style={{ width: '50%' }}>
                      <Tabs
                        defaultActiveKey="自有视频"
                        items={[
                          {
                            key: '自有视频',
                            label: '自有视频',
                            children: (
                              <ProTable
                                columns={columns}
                                search={false}
                                options={false}
                                // actionRef={actionRef}
                                dataSource={right_video}
                                pagination={{ pageSize: 10 }}
                                rowKey={(record) => record.id}
                                dateFormatter="string"
                                size="small"
                                scroll={{ y: 400 }}
                              />
                            ),
                          },
                          {
                            key: '平台视频',
                            label: '平台视频',
                            children: (
                              <ProTable
                                columns={columns2}
                                search={false}
                                options={false}
                                // actionRef={actionRef}
                                dataSource={right_video2}
                                pagination={{ pageSize: 10 }}
                                rowKey={(record) => record.id}
                                dateFormatter="string"
                                size="small"
                                scroll={{ y: 400 }}
                              />
                            ),
                          },
                        ]}
                      />
                    </div>
                  </div>
                ),
              },
            ]}
          />
        </Card>
      </ProForm>
      {/* 提交评估 */}
      <Modal
        title="提交确认"
        open={commitVisible}
        onOk={delOk}
        onCancel={() => setcommitVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Divider />
        <p>
          <InfoCircleTwoTone twoToneColor="#ffcc00" /> 确定要提交嘛？
        </p>
      </Modal>
      {/* 播放视频 */}
      <Modal
        centered
        open={viewButton}
        onCancel={() => setviewButton(false)}
        destroyOnClose={true}
        footer={null}
        closable={true}
        maskClosable={false}
        width={800}
      >
        <div style={{ paddingTop: '18px' }}>
          <video width="100%" height="100%" controls={true}>
            <source src={videoplay} type="video/mp4" />
          </video>
        </div>
      </Modal>
    </PageContainer>
  );
};
export default Becovery_assessment;
